package com.taotao.tools.mybatis.plugins.like;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.util.JdbcConstants;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.List;

/**
 * <p>
 *  mysql的实现
 * </p>
 *
 * @author youbeiwuhuan
 * @version 1.0.0
 * @date 2023/6/14 16:27
 */
@Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),})
public class MysqlLikeParamEscapeInterceptor extends AbstractLikeParamEscapeInterceptor {


    @Override
    protected List<Integer> findLikeParam(String prepareSql) {
        List<SQLStatement> stmtList = SQLUtils.parseStatements(prepareSql, JdbcConstants.MYSQL);
        if(null == stmtList || 0 == stmtList.size()){
            return null;
        }

        if (stmtList.size() > 1) {
            throw new RuntimeException("不支持多条sql");
        }

        LikeParamIndexMySqlASTVisitor visitor = new LikeParamIndexMySqlASTVisitor();
        stmtList.get(0).accept(visitor);

        return visitor.getIndexes();
    }


}
